from util.StringUtil import random_string
import time
class User:
    def __init__(self, name):
        self.name = name
        self.request_number=0
        self.cost_time=0.0
        self.node=None

    def set_node(self, node):
        self.node = node

    def set(self,key,value):
        self.node.set(key,value)

    def get(self,key):
        return self.node.get(key)

    def __str__(self):
        return ("user name:(%s)  request_number:(%d)  cost_time:(%f)  node:(%s)"
                % (self.name, self.request_number, self.cost_time, self.node))


    def write(self,*,write_number):
        """
        进行一次模拟的读写操作，写入write_number个数据。用户写入的数据格式为：(<user_name>:<number>,value)
        :param write_number: 模拟写操作的次数
        :return: 写入的键值对list [(key,value)]，方便后面进行验证
        """
        result=[]
        start_time=time.time()
        for i in range(int(write_number)):
            key=self.name+':'+str(i)
            value=key+':'+random_string(100)
            result.append((key,value))
            self.node.set(key,value)
        self.cost_time+=time.time()-start_time
        return result

    def read(self,*,read_number,same_data_ratio):
        """
        进行一次模拟的读写操作，读取read_number个数据。用户读数据的格式为<user_name>:<number> | 'same_data':<number>，其中same_data_ratio用来
        控制读入相同数据的比例，因为即使是不同的用户也有可能访问相同的数据，并且这类数据在实际数据中心环境中占比还是比较高的
        :param read_number: 读操作的次数
        :param same_data_ratio: 读取相同数据的比例
        :return: 键值对列表[(key,value)]
        """
        self.request_number+=1
        start_time=time.time()
        result=[]
        for i in range(int(read_number*(1-same_data_ratio))):
            key=self.name+':'+str(i)
            node,value=self.node.get(key)
            result.append((key,value))
        for i in range(int(read_number*same_data_ratio)):
            key='same_data:'+str(i)
            node,value=self.node.get(key)
            result.append((key,value))

        self.cost_time+=time.time()-start_time
        return result


